package zero.tech.wsnet.work;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import zero.tech.wsnet.data.Consts;
import zero.tech.wsnet.net.CacheClient;
import zero.tech.wsnet.net.WebClient;

public class HeartBeatWork extends Thread {
	private static Logger logger = LoggerFactory.getLogger(HeartBeatWork.class);

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(10 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			try {
				doHeartBeat();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void doHeartBeat() {
		Map<String, WebClient> clients = CacheClient.clients;
		long now = System.currentTimeMillis();
		for (WebClient client : clients.values()) {
			Long lastReceivePackTime = (Long) client.getAttribute(Consts.LAST_RECEIVE_PACK_TIME);
			if (lastReceivePackTime == null) {
				lastReceivePackTime = 0L;
			}
			if (now - lastReceivePackTime > 10 * 1000 * 12) {
				// 心跳超时,进行关闭连接
				logger.error("心跳超时");
				client.activeClose();
			}
		}
	}
}
